import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Layout from '../Layout/Layout.vue'
import Register from '../views/Register.vue'
import Person from '../views/Person.vue'
import House from '../views/House.vue'
import store from '../store';
import {ElMessage} from "element-plus"; // 引入 Vuex 存储

const routes = [
    {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect:'/login',
    children:[
    {
      path:'/home',
      name:'Home',
      component:Home,
      meta: { requiresAuth: true, requiresAdmin: true},
    },
    {
      path:'/person',
      name:'Person',
      component: Person,
      meta:{ requiresAuth: true , requiresAdmin: true},
    },
    {
      path:'/house',
      name:'House',
      component: House,
      meta:{ requiresAuth: true},
    }]
  },
  {
    path:'/login',
    name:'login',
    component: Login
  },
  {
  path:'/register',
  name:'register',
  component: Register,
  meta:{ requiresAuth: true ,requiresAdmin:true}
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)){
        // 需要认证的路由
        if (!store.getters.isAuthenticated) {
            next({
                path: '/login',
                query: { redirect: to.fullPath },
            });
        } else {
            if(to.matched.some(record => record.meta.requiresAdmin)){
                console.log("admin",store.getters.isAdmin);
                console.log("role",store.state.role);
                if(store.getters.isAdmin){
                    next();
                }else{
                    ElMessage.error('您没有权限访问该页面');
                    next({name:'House'});
                }
            }
            else{
                next();
            }
        }
    }
    else {
        next();
    }
});

export default router
